from EpisodeUtil import EpisodeUtil
from EpisodeRegex import EpisodeRegex
import os

class Renamer:
    
    def __init__(self, sourceDir, destDir=None, extensions=None):
        self.sourceDir = sourceDir
        self.destDir = sourceDir if destDir is None else destDir
        self.renamed = []
        self.extensions = extensions
        self.__regex = EpisodeRegex(extensions)
        self.__eParser = EpisodeUtil()
        self.__deepSearch = True
        
    def enableDeepSearch(self):
        self.__deepSearch = True
        
    def disableDeepSearch(self):
        self.__deepSearch = False
                   
    def rename(self):
        for file in os.listdir(self.sourceDir):
            filePathName = os.path.join(self.sourceDir, file)
            if self.__isDirAndDeepSearchEnable(filePathName):
                self.__recursivelyRename(filePathName)
            else:
                self.__tryRenameFile(file)
            
    def __recursivelyRename(self, filePathName):
        innerRenamer = Renamer(filePathName, self.destDir, self.extensions)
        innerRenamer.rename()

    def __tryRenameFile(self, file):
        match = self.__regex.search(file)
        if match != None:
            self.__renameFile(file, match)
        
    def __renameFile(self, fileName, match):
        episode = self.__eParser.createFromMatch(match)
        if self.__fileWasNotRenamedBefore(fileName, episode):
            filePath = "%s\\%s" % (self.sourceDir,fileName)
            fileRenamedPath = "%s\\%s" % (self.destDir, episode)        
            os.rename(filePath, fileRenamedPath)
            self.__addToRenamed(episode)  
                
    def __fileWasNotRenamedBefore(self, fileName, episode):
        return fileName != episode.__str__()
            
    def __addToRenamed(self, episode):
        self.renamed.append(episode)
        
    def __isDirAndDeepSearchEnable(self, file):
        return self.__deepSearch and os.path.isdir(file)